package com.ocom.aiot.controller;


import com.ocom.aiot.service.MjAppVerInfoService;
import com.ocom.aiot.service.MjDeviceInfoService;
import com.ocom.common.constant.AiotUrl;
import com.ocom.common.entity.aiot.EntityMjAppVerInfo;
import com.ocom.common.entity.aiot.EntityMjDeviceInfo;
import com.ocom.common.enums.MachEnum;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.utils.RespUtilMach;
import com.ocom.redis.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class MjDeviceStateController {

    private final Logger log = LoggerFactory.getLogger(MjAppVerInfoController.class);
    @Autowired
    private MjDeviceInfoService mjDeviceInfoService;

    @Autowired
    private MjAppVerInfoService mjAppVerInfoService;

    @Resource
    private RedisUtil redisUtil;




    // 3.5.门禁设备获取升级版本信息（getMjDeviceVersion）
    @GetMapping(value = AiotUrl.URL_Aiot_GetMjDeviceVersion)
    public RespMachMessage GetMjDeviceVersion(String deviceNo, String versionCode, Integer commMode) {
        //判断参数
        if (deviceNo == null) {
            log.error("获取门禁设备状态出厂号为空");
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }
        //根据出厂号查找设备状态
        EntityMjDeviceInfo entityMjDeviceInfo = null;
        try {
            entityMjDeviceInfo = mjDeviceInfoService.selectDeviceInfo(deviceNo);
            if (entityMjDeviceInfo == null) {
                log.error("获取门禁设备信息为空");
                return RespUtilMach.error(MachEnum.NOT_MACH);
            }
        } catch (Exception exception) {
            log.error("获取门禁设备信息失败" + exception.getMessage());
            return RespUtilMach.error(MachEnum.MACH_NOT_INFO);
        }
        // 4.修改数据库：
        //mj_device_info . comm_time = 当前系统时间   mj_device_info . comm_mode = #commMode
        try {
            redisUtil.set("HttpAiotMJMachCommTime:"+deviceNo,new Date());
            if(!entityMjDeviceInfo.getCommMode().equals(commMode)){
                mjDeviceInfoService.updateCommTimeCommMode(deviceNo, commMode);
            }
//            mjDeviceInfoService.updateCommTimeCommMode(deviceNo, commMode);
        } catch (Exception exception) {
            log.error("修改通讯时间和通信协议失败" + exception.getMessage());
            return RespUtilMach.error(MachEnum.NOT_COMMTIME_COMMMODE);
        }

        String appVer = entityMjDeviceInfo.getAppVer();

        //判断mj_device_info.appVerTab是否等于#{appVer}
        if (!versionCode.isEmpty() && !versionCode.equals(appVer)) {
            //更新数据
            try {
                //更新版本
                mjDeviceInfoService.updateAppVer(entityMjDeviceInfo.getComId(), entityMjDeviceInfo.getDeviceNo(), versionCode);
                appVer = versionCode;
            } catch (Exception exception) {
                log.error("更新设备当前版本（设备上报）失败" + exception.getMessage());
                return RespUtilMach.error(MachEnum.NOT_APPVER);
            }
        }

        // 6.firmwareUpdate=mj_device_info  . app_ver_tab ==”” ? 0 : (app_ver==app_ver_tab ? 0 : 1)
        //如果firmwareUpdate=1，从总库消费设备app版本信息mj_app_ver_info查app_ver匹配的记录
        //apkUrl = mj_app_ver_info . apk_file_url
        Integer firmwareUpdate = 0;
        String apkUrl = "";
        if (entityMjDeviceInfo.getAppVerTab().isEmpty() || appVer.equals(entityMjDeviceInfo.getAppVerTab())) {
            firmwareUpdate = 0;
        } else {
            firmwareUpdate = 1;
            //apkUrl = mj_app_ver_info . apk_file_url
            EntityMjAppVerInfo entityMjAppVerInfo = null;
            try {
                entityMjAppVerInfo = mjAppVerInfoService.GetMjAppVer(entityMjDeviceInfo.getAppVerTab());
                if (entityMjAppVerInfo == null) {
                    log.error("没有升级版本的信息");
                    return RespUtilMach.error(MachEnum.APPVER_NULL);
                }
            } catch (Exception exception) {
                log.error("更新设备当前版本（设备上报）失败" + exception.getMessage());
                return RespUtilMach.error(MachEnum.NOT_APPVER);
            }
            apkUrl = entityMjAppVerInfo.getApkFileUrl();
        }

        Map<String, Object> map = new HashMap<>();
        map.put("firmwareUpdate", firmwareUpdate);
        map.put("apkUrl", apkUrl);
        return RespUtilMach.success(map);
    }


    // 3.4.门禁设备签到（setMjDeviceCommTimeBySign）
    @GetMapping(value = AiotUrl.URL_Aiot_SetMjDeviceCommTimeBySign)
    public RespMachMessage SetMjDeviceCommTimeBySign(String deviceNo, Integer commMode) {
        //判断参数
        if (deviceNo == null) {
            log.error("门禁设备签到出厂号为空");
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }
        Map<String, Object> map = new HashMap<>();
        //根据出厂号查找设备记录
        EntityMjDeviceInfo entityMjDeviceInfo = null;
        try {
            entityMjDeviceInfo = mjDeviceInfoService.selectDeviceInfo(deviceNo);
            if (entityMjDeviceInfo == null) {
                //2.不存在则 comId=0,status=0;
                map.put("comId", 0);
                map.put("status", 0);
                map.put("saasNo", 2);
                return RespUtilMach.success(map);
            }
        } catch (Exception exception) {
            log.error("获取门禁设备信息失败" + exception.getMessage());
            return RespUtilMach.error(MachEnum.MACH_NOT_INFO);
        }
        // 3.判断endTime是否在有效期内，过期则 status=0;
        if (entityMjDeviceInfo.getEndTime() != null){
            if (entityMjDeviceInfo.getEndTime().getTime() < new Date().getTime()) {
                map.put("comId", entityMjDeviceInfo.getComId());
                map.put("status", 0);
                map.put("saasNo", entityMjDeviceInfo.getSaasNo());
                return RespUtilMach.success(map);
            }
        }

        //如果status=2,则更新门禁设备信息（通讯协议类型、最后通讯时间）
        if (entityMjDeviceInfo.getStatus() == 2) {
            try {
                redisUtil.set("HttpAiotMJMachCommTime:"+deviceNo,new Date());
                if(!entityMjDeviceInfo.getCommMode().equals(commMode)){
                    mjDeviceInfoService.updateCommTimeCommMode(deviceNo, commMode);
                }
//                mjDeviceInfoService.updateCommTimeCommMode(deviceNo, commMode);
            } catch (Exception exception) {
                log.error("修改通讯时间和通信协议失败" + exception.getMessage());
                return RespUtilMach.error(MachEnum.NOT_COMMTIME_COMMMODE);
            }
        }

        //ii)  如果mj_device_info . status==0，返回错误（错误码：0x0700）
        if (entityMjDeviceInfo.getStatus() == 0) {
            log.error("设备未激活" + entityMjDeviceInfo.getDeviceNo());
            return RespUtilMach.error(MachEnum.DeviceNotActive);
        }


        //iii)  	saasNo= mj_device_list. saas_no
        map.put("status", entityMjDeviceInfo.getStatus());
        //companyID = mj_device_list . com_id
        map.put("comId", entityMjDeviceInfo.getComId());
        map.put("saasNo", entityMjDeviceInfo.getSaasNo());
        return RespUtilMach.success(map);
    }

}
